#include "stdafx.h"

#include "ParticleHolderManager.h"

#include "ParticleHolder.h"
#include "game.h"

ParticleHolder* ParticleHolderManager::m_poolParticleHolder[MAX_PARTICLE_HOLDERS] = {NULL};
int ParticleHolderManager::m_count = 0;

ParticleHolderManager::ParticleHolderManager()
{
	m_count = 0;
}

ParticleHolderManager::~ParticleHolderManager()
{
}

void ParticleHolderManager::Render()
{
	for(int i=0;i<m_count;i++)
	{	
		m_poolParticleHolder[i]->render();
	}
}
void ParticleHolderManager::Update()
{
	int i = 0;
	bool active;

	while( i < m_count )
	{
		active = m_poolParticleHolder[i]->IsActive();
		if( !active || 
			( active && m_poolParticleHolder[i]->IsFinished() ) ||
			!m_poolParticleHolder[i]->IsVisible()
			)
		{
			m_poolParticleHolder[i]->SetVisible( false );

			if(m_poolParticleHolder[i]->IsSelfManagement())
			{
				SAFE_DELETE(m_poolParticleHolder[i]);
			}

			for( int j = i + 1; j < m_count; j++ )
			{
				m_poolParticleHolder[j - 1] = m_poolParticleHolder[j];
			}
			m_count--;
		}
		else
		{
			i++;
		}
	}

	for(int i=0;i<m_count;i++)
	{	
		m_poolParticleHolder[i]->update(getGame()->GetGameplayTimeStep());
	}
}

void ParticleHolderManager::Add( ParticleHolder* ph )
{
	int id = -1;
	for( int i = 0; i < m_count; i++ )
	{
		if( m_poolParticleHolder[i] == ph )
		{
			id = i;
		}
	}
	if( id < 0 )
	{
		//GX_ASSERT( m_count < MAX_PARTICLE_HOLDERS );
		id = m_count;
		m_count++;
	}

	m_poolParticleHolder[id] = ph;
	m_poolParticleHolder[id]->SetVisible( true );
}

void ParticleHolderManager::Remove( ParticleHolder* ph )
{
	for( int i = 0; i < m_count; i++ )
	{
		if( m_poolParticleHolder[i] == ph )
		{
			m_poolParticleHolder[i]->SetVisible( false );
			for( int j = i + 1; j < m_count; j++ )
			{
				m_poolParticleHolder[j - 1] = m_poolParticleHolder[j];
			}
			m_count--;
			break;
		}
	}
}
